from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
import ast
import json

# from config import OPENAI_API_KEY
from langchain.memory import ChatMessageHistory
import sys
import pymysql
import os

# OPENAI_API_KEY = "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"
OPENAI_API_KEY = "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"

os.environ["http_proxy"] = "http://127.0.0.1:10808"
os.environ["https_proxy"] = "http://127.0.0.1:10808"


def dataBase(questionID):
    # 连接数据库，创建连接对象connection
    # 连接对象作用是：连接数据库、发送数据库信息、处理回滚操作（查询中断时，数据库回到最初状态）、创建新的光标对象
    connection = pymysql.connect(
        host="www.yym-free.com",
        user="fuchuang",
        password="fuchuang",
        db="fuchuang",
        port=3306,
    )
    cur = connection.cursor()
    # 获取全部食品的信息
    cur.execute("SELECT * FROM dialog WHERE questionID = %s", (questionID,))
    all = cur.fetchall()
    k = 0
    new_list = []
    for i in all:
        # 获取对话的信息
        # index = i[0]
        # list[k]["askStr"] = i[2]
        # list[k]["answer"] = i[3]
        # k = k + 1
        new_item = {
            "askStr": i[2],
            "answerStr": i[3],
            # 其他字段...
        }
        # 将修改后的字典添加到新的列表中
        new_list.append(new_item)
        print(new_item)
    connection.commit()
    connection.close()
    # print(list)
    return new_list


def list_to_chat_history(chat_history: list) -> list:
    # 创建一个ChatMessageHistory实例
    message_history = ChatMessageHistory()

    # 遍历对话记录并添加到ChatMessageHistory中
    for entry in chat_history:
        message_history.add_user_message(entry["askStr"])
        message_history.add_ai_message(entry["answerStr"])
    # print(message_history)
    return message_history


def convert_chat_history_to_list(message_history: ChatMessageHistory) -> list:
    chat_history_list = []
    for message in message_history.messages:
        if isinstance(message, HumanMessage):
            chat_history_list.append({"sender": "User", "message": message.content})
        elif isinstance(message, AIMessage):
            chat_history_list.append({"sender": "LLM", "message": message.content})
    return chat_history_list


def chat_with_llm(user_input: str, chat_history: list) -> dict:
    try:
        prompt = ChatPromptTemplate.from_messages(
            [
                (
                    "system",
                    "You are a helpful assistant. Answer all questions to the best of your ability.",
                ),
                MessagesPlaceholder(variable_name="messages"),
            ]
        )
        # 创建LLM实例
        llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
        output_parser = StrOutputParser()
        chain = prompt | llm | output_parser
        message_history = list_to_chat_history(chat_history)
        message_history.add_user_message(user_input)
        response = chain.invoke(
            {
                "messages": message_history.messages,
            }
        )
        chat_history.append({"askStr": user_input, "answerStr": response})
        # 打印返回的数据
        print(response)
        # return {
        #     "success": True,
        #     "response": response,
        #     # "updated_chat_history": chat_history,
        # }
    except Exception as e:
        print(e)
        # return {"success": False, "response": None, "error": str(e)}


if __name__ == "__main__":

    # # 用户本次的问题
    user_input = sys.argv[1]
    # # 此次问题的ID
    questionID = sys.argv[2]
    # questionID = sys.argv[2]
    # questionID = 1
    quesID = int(questionID)
    # 获取对话历史
    list = dataBase(quesID)
    # user_input = "请你给出几个题目例子"
    # questionID = 1
    # 获取答案
    # print(list)
    chat_with_llm(user_input, list)
